<template>
  <div class="afterInvestDel-page">
    <pubChunk :mt="20">
      <span slot="title">收益风险指标</span>
      <el-table
        v-loading="listLoading_riskIndicators"
        :data="list_riskIndicators"
        fit
        default-expand-all
        size="mini"
        style="width: 100%"
        :cell-class-name="cellClass"
        :cell-style="{ padding: '8px 0' }"
        :header-cell-style="{ color: '#333' }"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        row-key="rowKey"
      >
        <!-- <el-table-column
          prop="name"
          label="名称"
          min-width="120"
          show-overflow-tooltip
        >
          <template slot-scope="{ row, $index }">

          <span
                v-if="row.classifyId && !row.strategyId"
              >
                <span v-show="row.hasNetWorth && row.classifyId">
                  <span
                    @click="loadClassifyChildTable(row, $index, row.treeHas)"
                  >
                    <svg v-show="!row.treeHas" class="icon svg-icon" aria-hidden="true">
                      <use xlink:href="#icon-a-Icon-shouqi"></use>
                    </svg>
                    <svg v-show="row.treeHas" class="icon svg-icon" aria-hidden="true">
                      <use xlink:href="#icon-Icon-zhankai"></use>
                    </svg>
                  </span>
                  <span
                    style="cursor: pointer; color: #1890ff; margin-right: 2px;"
                  >
                    [分类]
                  </span>
                </span>
                <span
                  style="cursor: pointer; color: #1890ff;"
                  @click.stop="groupDeltailHandle(row.classifyId)"
                >
                  {{ row.name }}
                </span>
              </span>
              <span
                v-else-if="row.strategyId"
                style="margin-left: 20px; cursor: pointer; color: #1890ff;"
                @click.stop="strategyDeltailHandle(row.strategyId)"
              >
                [投资]
                <span>{{ row.name }}</span>
              </span>
              <span v-else style="cursor: pointer; color: #666;">
                {{ row.name }}
              </span>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="name"
          label="名称"
          fixed="left"
          :width="flexColumnWidth('名称', 'name', list_riskIndicators)"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.strategyId"
              :title="row.name"
              style="cursor: pointer; color: #1890ff"
              @click.stop="groupDeltailHandle(row.strategyId)"
            >
              {{ row.name }}
            </span>
            <span v-else :title="row.name" style="cursor: pointer; color: #666">
              {{ row.name }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="nominalAmount"
          label="名义金额(万元)"
          align="center"
        >
          <template slot-scope="{ row }">
            <span v-if="row.nominalAmount">{{ row.nominalAmount }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="initMoney" label="资产金额(万元)" align="center">
          <template slot-scope="{ row }">
            <span v-if="row.initMoney">{{ row.initMoney }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="权重" align="center">
          <template slot-scope="{ row }">
            <span v-if="row.weight">{{ row.weight | toFixed2 }}%</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="incomeRate"
          label="收益率"
          min-width="100"
          align="center"
        >
          <template slot-scope="{ row }">
            <span
              v-if="row.incomeRate"
              :class="row.incomeRate >= 0 ? 'positiveFc' : 'negativeFc'"
            >
              {{ row.incomeRate }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="annualizedIncomeRate"
          label="年化收益率"
          align="center"
        >
          <template slot-scope="scope">
            <span
              v-if="scope.row.annualizedIncomeRate"
              :class="
                scope.row.annualizedIncomeRate >= 0
                  ? 'positiveFc'
                  : 'negativeFc'
              "
            >
              {{ scope.row.annualizedIncomeRate }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="annualFluctuationsRate"
          label="年化波动率"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="sharpeRate"
          label="夏普比率"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="maximumDrawdownRate"
          label="最大回撤"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="calmarRate"
          label="卡玛比率"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="maxBackIncomDay"
          label="最大回撤回补期"
          min-width="92"
          align="center"
        >
          <template slot-scope="{ row }">
            <span v-if="row.maxBackIncomDay">{{ row.maxBackIncomDay }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="maxNotByNewHightDay"
          label="最大不创新高天数"
          min-width="100"
          align="center"
        >
          <template slot-scope="{ row }">
            <span v-if="row.maxNotByNewHightDay">
              {{ row.maxNotByNewHightDay }}
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="investWinningRate"
          label="投资胜率"
          align="center"
        ></el-table-column>
      </el-table>
    </pubChunk>
  </div>
</template>
<script>
import pubChunk from "@/components/investComn/pubChunk.vue";

import {
  getClassRiskRateByClassifyId,
  getStrategyClassifyExt,
} from "@/api/groupManage";
import {
  // getRiskRateById,
  findClassifyByCompositionId,
} from "@/api/combManage";
import { getIndexRiskByIndexTypeAndTime } from "@/api/policyManage";
import mixin from "./mixins";
// import debounce from 'lodash/debounce'
import { getMaxLength } from "@/utils/pro";

export default {
  mixins: [mixin],
  components: { pubChunk },
  data() {
    return {
      chart_date: [],
      info: {},
      list_riskIndicators_key1: 1,
      list_riskIndicators: [], // 收益风险指标
      tip_list_riskIndicators: 1,

      _list_riskIndicators: [], // 保存基础 收益风险指标
      list_riskIndicators_key2: 100,
      nominalAmount: "",
      combTree: [],
      combTreeStrategyList: [],
      listLoading_riskIndicators1: false,
      listLoading_riskIndicators4: false,
      listLoading_riskIndicators: false,
    };
  },
  props: {
    contrastOptionsObj: {
      type: Array | Object,
    },
    chart1List: {
      type: Array | Object,
    },
    chart_date_parent: {
      type: Array | Object,
    },
    indexTypes: {
      type: String | Number,
      default: "",
    },
  },
  created() {},
  mounted() {},
  watch: {},
  methods: {
    init(info) {
      this.info = info;
      this.chart_date = this.chart_date_parent;
      this.getriskIndicators(); // 风险指标
    },
    // 收益风险指标
    getriskIndicators() {
      this.listLoading_riskIndicators = true;
      getClassRiskRateByClassifyId({
        classifyId: this.classifyId,
        userId: this.userId,
      }).then((res) => {
        // this.list_riskIndicators[0].classifyId = this.classifyId
        console.log("风险指标", res);
        this.list_riskIndicators[0] = res.body;
        this.list_riskIndicators[0].name = this.info.classfyName;
        this.list_riskIndicators[0].rowKey = 1;
        this.list_riskIndicators[0].strategyId = null;
        this.list_riskIndicators[0].netWorthExtendBeanList =
          res.body.classifyNetWorthExtendBeans;
        this.list_riskIndicators = this.flatRecursionHandle(
          this.chart1List,
          this.list_riskIndicators
        );
        this.getStrategyClassifyExt(this.classifyId);
        this.getIndexRiskByIndexTypeAndTime(this.indexTypes);
      });
    },
    getStrategyClassifyExt() {
      this.listLoading = true;
      getStrategyClassifyExt({ classifyId: this.classifyId }).then((res) => {
        console.log("投资列表", res);
        this.listLoading = false;
        res.body.map((item, i) => {
          item.rowKey = i + 2;
          item.name = item.strategyName;
          item = Object.assign(item, item.riskIndicatorsBean);
        });

        this.strategyPortfolioDetials = res.body;
        this.$set(
          this.list_riskIndicators[0],
          "children",
          this.flatRecursionHandle(this.chart1List, res.body)
        );
      });
    },
    // 收益风险指标 指数
    getIndexRiskByIndexTypeAndTime(indexType) {
      this.listLoading_riskIndicators = true;
      getIndexRiskByIndexTypeAndTime({
        indexType,
        startTime: this.chart_date[0],
        endTime: this.chart_date[1],
      }).then((res) => {
        console.log("风险指标 指数", res);
        this.listLoading_riskIndicators = false;
        this.list_riskIndicators = [this.list_riskIndicators[0]];
        Object.keys(res.body).forEach((index) => {
          const name = this.contrastOptionsObj[index];
          this.list_riskIndicators.push({
            name,
            rowKey: index + 10000,
            netWorthExtendBeanList: res.body[index].scopeIndexVos,
            ...res.body[index],
          });
        });
        this.list_riskIndicators = this.flatRecursionHandle(
          this.chart1List,
          this.list_riskIndicators
        );
      });
    },

    riskRecursionHandle(resList, list) {
      list.map((items, i) => {
        const resList_i = resList.findIndex((item) => item.name == items.name);
        if (resList_i != -1) {
          const res = resList[resList_i];
          list[i] = {
            strategyId: items.strategyId,
            classifyId: items.classifyId,
            children: items.children,
            rowKey: items.rowKey,
            weight: items.weight,
            initMoney: items.initMoney,
            nominalAmount: items.nominalAmount,
            ...res,
          };
        } else if (items.children) {
          // 分类
          items.children.forEach((_) => {
            list[i] = {
              classifyId: items.classifyId,
              annualFluctuationsRate: "--",
              sharpeRate: "--",
              maxBackIncomDay: "--",
              maximumDrawdownRate: "--",
              calmarRate: "--",
              investWinningRate: "--",
              ...list[i],
            };
          });
        }
        if (items.children) {
          this.riskRecursionHandle(resList, items.children);
        }
      });
      return list;
    },
    sublistHandle() {
      this.listLoading_riskIndicators2 = true;
      findClassifyByCompositionId({
        ...this.params,
      }).then((res) => {
        console.log("分类列表", res);
        this.listLoading_riskIndicators2 = false;
        this.listLoading = false;
        if (res.body.length > 1) {
          res.body.map((item, i) => {
            item.rowKey = i + 2;
            item.name = item.classfyName;
            item.weight = item.compositionWeight;
            item = Object.assign(item, item.riskIndicatorsBean);
          });
          this.classfyList = res.body;
          this.$set(this.list_riskIndicators[0], "children", res.body);
        } else {
          this.$set(this.list_riskIndicators[0], "children", undefined);
        }
      });
    },
    strategySublistHandle1() {
      this.listLoading_riskIndicators4 = true;
      const children = JSON.parse(JSON.stringify(this.combTree));
      children.forEach((item) => {
        item.children = item.classifyStrategyExt;
        item.rowKey = "F" + item.classifyId;
        item.name = item.classfyName;
        item.hasNetWorth = true;
        item.children.forEach((el) => {
          el.rowKey = "C" + el.strategyId;
          el.name = el.strategyName;
          el.initMoney = el.initialMoney;
          el.hasNetWorth = true;
        });
      });
      this.listLoading_riskIndicators4 = false;
      this.$set(this.list_riskIndicators[0], "children", children);
      console.log("分类列表1", this.list_riskIndicators);
    },
    strategyDeltailHandle(id) {
      this.$router.push({
        path: `/policyManage/netWorthAnalysis/${id}`,
        query: {
          userId: this.userId,
        },
      });
    },
    loadChildTable(row, index, treeHas) {
      if (treeHas) {
        this.classfyList.forEach((item) => {
          item.treeHas = false;
          item.hasNetWorth = false;
        });
        this.list_riskIndicators.splice(1, 0, ...this.classfyList);
      } else {
        this.list_riskIndicators = this.list_riskIndicators.filter((item) => {
          if (item.compositionName === row.name && item.classifyId) {
            return false;
          }
          if (item.strategyId) {
            return;
          }
          return item;
        });
      }
      row.treeHas = !treeHas;

      /**
       * 组合投资只有一个分类时会默认不展示分类
       */
      if (treeHas) {
        if (!this.classfyList.length) {
          this.strategySublistHandle1();
        }
      } else {
        this.list_riskIndicators = this.list_riskIndicators.filter((item) => {
          if (item.classifyId === row.classifyId && item.strategyId) {
            return false;
          }
          return item;
        });
      }

      this.list_riskIndicators = this.flatRecursionHandle(
        this.chart1List,
        this.list_riskIndicators
      );
    },
    /**
     * 不足的数据从echart图表中补充
     */
    flatRecursionHandle(resList, list) {
      list.map((items, i) => {
        const resList_i = resList.findIndex((item) => item.name == items.name);
        if (resList_i != -1) {
          const res = resList[resList_i];
          list[i] = {
            strategyId: items.strategyId,
            classifyId: items.classifyId,
            children: items.children,
            rowKey: items.rowKey,
            weight: items.weight,
            initMoney: items.initMoney,
            nominalAmount: items.nominalAmount,
            hasNetWorth: items.hasNetWorth,
            treeHas: items.treeHas,
            compositionName: items.compositionName,
            indexType: items.indexType,
            ...res,
          };
        }
      });
      return list;
    },
    groupDeltailHandle(id) {
      this.$router.push({
        path: `/afterManage/investList/details/${id}`,
      });
    },
    /**
     * 表格数据单行显示内边距为0
     */
    cellClass(row) {
      if (
        (!row.column.label ||
          row.column.label === "名称") &&
        this.maxNameWidth < 400
      ) {
        return "cell-pad-0 nowrap";
      } else if (this.maxNameWidth >= 400) {
        return "cell-pad-0 clamp2Ellipsis";
      }
      return "";
    },
    /**
     * table column 自适应列宽
     * @param label 表名
     * @param prop 表格数据
     * @param tableData 表格数据
     */
    flexColumnWidth(label, prop, tableData) {
      const arr = tableData.map((x) => x[prop]);
      arr.push(label);
      if (getMaxLength(arr) + 80 >= 400) {
        this.maxNameWidth = 400
      }else {
        this.maxNameWidth = getMaxLength(arr) + 80
      }
      return this.maxNameWidth
    },
  },
};
</script>
<style lang="scss" scoped>
.afterInvestDel-page {
  .svg-icon {
    width: 18px;
    height: 18px;
    font-size: 18px;
    vertical-align: -0.3em;
    cursor: pointer;
  }
  .title {
    font-size: 26px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #262626;
  }
}
</style>
